package top.forgirl.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.forgirl.domain.Demand;
import top.forgirl.domain.Material;
import top.forgirl.domain.dto.DemandDo;
import top.forgirl.mapper.DemandMapper;

import java.util.List;

@Service
public class DemandService {

    @Autowired
    private DemandMapper demandMapper;
    @Autowired
    private MaterialService materialService;

    public List<Demand> list(DemandDo demandDo, int offset, int count) {
        return demandMapper.list(demandDo, offset, count);
    }

    public Integer countPage(int numOfPage, String cId) {
        return demandMapper.countPage(numOfPage, cId);
    }

    public Demand deleteDemand(String cId, String dId) {
        Demand demand = demandMapper.selectOne(cId, dId);
        if (demand != null) {
            demandMapper.delete(cId, dId);
            return demand;
        }
        return null;
    }

    public Demand insert(DemandDo demandDo) {

        Material material = materialService.insertMaterial(demandDo.getDName(), demandDo.getPrice());
        if (material == null) {
            return null;
        }

        Demand demand = new Demand();
        demand.setCId(demandDo.getCId());
        demand.setNumber(demandDo.getNumber());
        demand.setContainCostFlag(demandDo.getContainCostFlag());
        demand.setDeadline(demandDo.getDeadline());
        demand.setDId(material.getDId());
        demand.setToLocation(demandDo.getToLocation());

        int result = demandMapper.insert(demand);
        if (result > 0) {
            return demand;
        } else {
            return null;
        }

    }

    public Demand update(Demand demand) {

        int result = demandMapper.update(demand);
        if (result > 0) {
            return demandMapper.selectOne(demand.getCId(), demand.getDId());
        }
        return null;
    }
}
